<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'

import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/useMessage'
import { Query } from '@/api'

const { query } = useRoute()
//看板标题
const title = computed(() => {
  return query.label || ''
})
const currentEnv = import.meta.env.DEV
const baseURL = window.location.origin
//工单信息
const data = ref<any[]>([])
const cols = ref<any[]>([])
const esdlist = ref<any[]>([])
//NPM信息

const imageCols = ref<any[]>([])
const imageList = ref<any[]>([])

const currentIndex = ref(-1)
const maxZIndex = ref(1)
const showCard = (index: number) => {
  maxZIndex.value += 1
  currentIndex.value = index
}

const closeCard = () => {
  currentIndex.value = -1
}

//刷新周期
const flushTimer = ref()
//底部责任人
const otherInfo = ref({
  PD: '',
  QA: '',
  PE: ''
})
//设备状态
const statusList = ref([])

//线别
const line = ref([])
const lineList = ref()
//切换线别
const changeLine = async () => {
  //获取责任人信息
  const match =
    lineList.value.length && lineList.value.filter((item: any) => item.Value == line.value)
  // otherInfo.value = match.length && match[0]
  // 先关闭定时器再重新启动刷新周期
  stopTimer()
  //开始循环获取数据GetKBInfo
  startTimer()
}

const doLine = (line: Array<string>) => {
  return line.map((item: string) => ({ Value: item }))
}

//获取数据
const getKBInfo = async () => {
  let lineStr :any[] = []
  if (line.value.length > 0) {
    lineStr = doLine(line.value)
  }
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo`,
    jsonData: lineStr,
    spName:''
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const {esdInfo,masterInfo } = res.data
  // imageList.value = npmInfo || []
  esdlist.value = esdInfo.ESDData || []

}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { npmFieldInfo, ctInfo, woFieldInfo, lineInfo,statusInfo } = res.data
  lineList.value = lineInfo || []
  cols.value = woFieldInfo
  imageCols.value = npmFieldInfo
  statusList.value = statusInfo || []


  //刷新时间
  flushTimer.value = ctInfo.length && ctInfo[0].CT
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【产品编号】后重新开始
// 2.循环过程中，重新选择【产品编号】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)
const getImageUrl = (list: any) => {
  if(currentEnv){
    return new URL(`/src/assets/deviceImages/${list.ImageName}.png`, import.meta.url).href
  } else {
    return `${baseURL}/deviceImages/${list.ImageName ? list.ImageName : '1-8'}.png`
  }
}
// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value * 1000
  timerId.value = window.setInterval(getKBInfo, timer)
}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})

onMounted(() => getPageInfo())
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="`${title}` + '看板'" />
    <section class="board-content">
      <div class="flex justify-between other-info">
        <MyBox title="" style="width: 100%;margin-top: 10px">
          <template v-slot:main>
            <div class="flex items-center justify-between">
              <p class="select-container">
                <el-select
                  multiple
                  collapse-tags
                  v-model="line"
                  style="width: 200px"
                  placeholder="请选择线别"
                  @change="changeLine"
                >
                  <el-option
                    v-for="(item, index) in lineList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </p>
              <div style="width: 80%;" class="flex items-center justify-between status-info">
                <p v-for="(item, index) in statusList" :key="index" class="flex items-center">
                  <span class="status-color" :style="{ background: item.color }">
                      <img style="width: 50px" :src="getImageUrl(item)" alt="Image"/>
                  </span>
                  <span class="status-text">{{ item.Name }}</span>
                </p>
              </div>

            </div>
            <div class=" ">

            </div>
          </template>
        </MyBox>
      </div>

      <div class="flex justify-between other-info row" v-for="(item, index) in esdlist" :key="index">
        <MyBox title="" :key="index" style="width: 100%">
          <template v-slot:main>
            <el-row>
              <el-col :span="4">
                <h4 class="text-title">线体：{{ item.Line }}</h4>
                <h4 class="text-title">工单：{{ item.WO }}</h4>
              </el-col>
              <el-col :span="20">
                <div class="image-list flex flex-wrap">
                  <div style="width:12%;" class="image-card" v-for="(i,idx) in item.StationData" :key="idx">
                    <div class="flex flex-wrap" style="justify-content: center;">
                      <img style="width: 25%" v-for="(img,imgIdx) in i.StatusData" :src="getImageUrl(img)" alt="Image" :key="imgIdx"/>
                    </div>
                    <p class="device-text">{{ i.StationName }}</p>
                  </div>
                </div>
              </el-col>
            </el-row>
          </template>
        </MyBox>
      </div>

    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.text-title {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-left: 10px;
}
.select-container ::v-deep .el-tag.el-tag--info{
  background: none;
  font-size: 22px;
  color: #00aeff;
}
.select-container ::v-deep .el-tag__close {
  display: none !important;
}

/* 可选：如果标签右侧有多余间距，可去除 */
.select-container ::v-deep .el-tag {
  padding-right: 8px !important; /* 原标签默认右侧有供删除按钮使用的间距，可适当减小 */
}
.npm-info {
  margin-top: 10px;
  height: 200px;
  overflow-y: visible;
}
.throws {
  margin-top: 80px;
}
.throws-top3-title {
  position: absolute;
  top: 20px;
  right: 130px;
  font-size: 18px;
}
.throws-top3-chart {
  position: absolute;
  width: 300px;
  right: 10px;
  top: 10px;
}

.row-box-wrapper {
  overflow: visible;
}
.status-info {
  p {
    margin-left: 26px;
  }
  position: absolute;
  right: 28px;
  top: 15px;
  .status-color {
    display: inline-block;
    width: 50px;
    height: 50px;
    margin-right: 8px;
  }
  .status-text {
    font-size: 26px;
    color: #8fe1ff;
  }
}
.image-list {
  width: 100%;
  margin: 30px 0 0 0;
}
.image-card {
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
  cursor: pointer;
  margin: 0 0 0.5% 0.5%;
  padding: 10px 5px;
  background: #045e88;
  .device-text{
    font-size: 14px;
    text-align: center;
    margin-top: 5px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .overlay {
    position: absolute;
    top: -200%;
    left: 50px;
    width: 300px;
    padding: 15px;
    transition: opacity 0.4s ease;
    border: 2px solid #00aeff;
    background: #040d4c;
    /* 左侧箭头 */
    .arrow {
      position: absolute;
      width: 0;
      height: 0;
      border-style: solid;
      transition: all 0.4s ease;
      // opacity: 0;
    }
    .arrow-left {
      top: 50%;
      left: -15px;
      transform: translateY(-50%);
      border-width: 15px 15px 15px 0;
      border-color: transparent rgba(46, 152, 201, 1) transparent transparent;
    }
    h3 {
      color: white;
      border: 2px solid #00aeff;
      span {
        display: inline-block;
        // float: right;
      }
      margin-bottom: 10px;
    }
    p {
      color: white;
      span {
        float: right;
        display: block;
      }
      margin-bottom: 10px;
    }
    .close-btn {
      color: #8fe1ff;
      border-radius: 2px;
      border: 1px solid #8fe1ff;
      padding: 2px 10px;
    }
  }
}

.row {
  margin: 15px auto 20px;
}
.icon {
  width: 100%;
}

.other-info {
  color: #8fe1ff;
  font-size: 24px;
  .flex {
    width: 99%;
    margin: 0 auto;
  }
}

.el-select-dropdown__item {
  font-size: 18px;
}
</style>
